package com.ego.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ego.admin.dao.SysLoginLogDao;
import com.ego.admin.po.SysLoginLog;
import com.ego.admin.po.SysAdmin;
import com.ego.admin.service.SysLoginLogService;
import com.ego.admin.util.IpUtil;
import com.ego.admin.vo.SysLoginLogVo;
import com.ego.common.util.AddressUtil;
import com.ego.common.vo.PageVo;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @program: ego
 * @description:
 * @author: KamTang
 * @create: 2023-02-16 16:07
 **/
@Service
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogDao, SysLoginLog> implements SysLoginLogService{

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addLoginReport(HttpServletRequest request) throws UnsupportedEncodingException {
        SysAdmin admin = (SysAdmin) SecurityUtils.getSubject().getPrincipal();
        SysLoginLog loginLog = new SysLoginLog();
        loginLog.setUsername(admin.getUsername());
        loginLog.setIp(IpUtil.getIpAddress(request));
        loginLog.setLocation(AddressUtil.getCityInfo(IpUtil.getIpAddress(request)));
        // 获取客户端操作系统
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        // 获取浏览器
        Browser browser = userAgent.getBrowser();
        // 获取操作系统
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        loginLog.setUserSystem(operatingSystem.getName());
        loginLog.setUserBrowser(browser.getName());
        loginLog.setLoginTime(new Date());
        this.baseMapper.insert(loginLog);
    }

    @Override
    public PageVo<SysLoginLog> findLoginLog(Map<String, Object> params) {
        return null;
    }

    @Override
    public List<Map<String, Object>> loginReport(String username) {
        return null;
    }

    @Override
    public SysLoginLogVo getLastLoginInfo(String username) {
        List<SysLoginLog> logs = this.baseMapper.selectList(new QueryWrapper<SysLoginLog>()
                .eq("username", username).orderByDesc("login_time"));
        // 第一次登录
        if (logs.size() == 1) {
            return logs.get(0).toVo();
        } else {
            return logs.get(1).toVo();
        }
    }
}
